package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sentCode(String phone, HttpSession session) {
        //判断手机号是否正确
        if(!RegexUtils.isPhoneInvalid(phone)){
            //不正确，返回错误信息
            return Result.fail("手机号格式错误");
        }
        //符合后生成6位验证码
        String code = RandomUtil.randomNumbers(6);
//        //将验证码保存到session
//        session.setAttribute("code",code);
        //将验证码保存到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone, code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //发送验证码
        log.debug("发送的验证码时：{}",code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //判断手机号和验证码是否正确
        String phone = loginForm.getPhone();
//        if(!RegexUtils.isPhoneInvalid(phone)){
//            //不正确，返回错误信息
//            return Result.fail("手机号格式错误");
//        }
        //校验验证码
//        Object code = session.getAttribute("code");
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        String code1=loginForm.getCode();
       /* if(code == null || !code.equals(code1)){
            //不正确，返回错误信息
            return Result.fail("验证码错误");
        }*/
        //根据手机号查询用户
        User user = query().eq("phone", phone).one();
        if(user==null){
            //用户不存在，创建新用户并保存
            User user1=new User();
            //根据手机号创建，并生成随机姓名
            user1.setPhone(phone);
            user1.setNickName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
            save(user1);
        }

        /*//保存到session
        session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));
        return Result.ok();*/
        //  保存用户信息到redis
        //先生成token作为登陆令牌
        String token= UUID.randomUUID().toString(true);
        //将user转为hash对象存储
        UserDTO userDTO=BeanUtil.copyProperties(user,UserDTO.class);
        Map<String,Object> userMap=BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create().
                setIgnoreNullValue(true).
                setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));
        //存储
        String tokenKey=LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        //设置token有效期
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL,TimeUnit.HOURS);
        //最后返回token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //1 获取当前用户
        Long userId= UserHolder.getUser().getId();
        //2 获取日期
        LocalDateTime time=LocalDateTime.now();
        //3拼接key
        String keysuffix=time.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=USER_SIGN_KEY+userId+keysuffix;
        //4 获取今日是本月第几天
        int day=time.getDayOfMonth();
        //5 写入redis setbit key offset 1
        stringRedisTemplate.opsForValue().setBit(key,day-1,true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        //统计本月到今天位置连续签到次数
        //1 获取当前用户
        Long userId= UserHolder.getUser().getId();
        //2 获取日期
        LocalDateTime time=LocalDateTime.now();
        //3拼接key
        String keysuffix=time.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key=USER_SIGN_KEY+userId+keysuffix;
        //4 获取今日是本月第几天
        int day=time.getDayOfMonth();
        //5 获取从开始到今天的签到记录 bitfield bm1 get u1 0
        List<Long> list = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create().
                get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0));
        if(list==null||list.isEmpty()){
            return Result.ok(0);
        }
        Long num=list.get(0);
        if(num==null || num ==0){
            //要么空要么签到次数为0
            return Result.ok(0);
        }
        //6统计连续签到次数
        int count=0;
        while (true){
            //右移一位，判断是否为0
            if((num&1)==0){
                //最后一位是0
                break;
            }else{
                //最后一位是1，计数+1
                count++;
            }
            num >>>= 1;
            //也可以写成 num=num >> 1;
        }
        return Result.ok(count);
    }

    public List<User> list(){
        //查询前一千条用户
        List<User> list= query().orderByDesc("id").last("limit 1000").list();
        return list;
    }
}
